<template>
	<view class="page" @click="closeMenuIfOpen">
		<!-- 主内容区 -->
		<view class="main-content">

			<!--  学校LOGO，仅在没有消息时显示 -->
			<view class="image-logo-content" v-if="messages.length === 0">
				<image class="logo" style="width: 160rpx; height: 160rpx; background-color: #eeeeee;"
					src="../../static/QCU_LOGO.jpg"></image>
			</view>
			<view class="text-app-name-box" v-if="messages.length === 0">
				<text>{{appName}}</text>
			</view>
			<!--  悬浮球  -->
			<view class="float-ball-container">
				<!-- 展开状态的菜单 -->
				<view class="expanded-menu" 
					v-if="showFloatMenu" 
					:class="{'closing-menu': closingMenu}"
					@click.stop>
					<!-- <view class="menu-header">
						<text class="menu-title">{{ currentLang === 'zh' ? '菜单' : 'Menu' }}</text>
						<view class="close-btn" @click.stop="toggleFloatMenu">×</view>
					</view> -->
					<view class="menu-items">
						<view
							v-for="(item, index) in floatMenuItems"
							:key="index"
							class="menu-item"
							@click.stop="handleFloatMenuClick(item.action)">
							<view class="menu-icon">
								<text class="icon-text">{{item.icon}}</text>
							</view>
							<!-- <text class="menu-label">{{item.label}}</text> -->
						</view>
					</view>
				</view>

				<!-- 自定义悬浮球实现 -->
				<view 
					class="custom-float-ball"
					:class="{ 'float-ball-hidden': showFloatMenu }"
					@click.stop="handleFloatBallTouch"
					:style="ballStyle">
				</view>
			</view>
			<!-- 聊天内容区 -->
			<scroll-view class="chat-container" :class="{ 'chat-container-expanded': messages.length > 0 }" id="chat-container" scroll-y="true" :scroll-top="scrollTop"
				@scrolltolower="onScrollToLower" @scroll="onScroll" ref="chatScrollView"
				:style="{ height: `${scrollHeight}px` }">

				<!-- 欢迎卡片，仅在没有消息时显示 -->
				<view class="welcome-card" v-if="messages.length === 0">
					<text class="welcome-text">{{ t('welcome.text') }}</text>
				</view>

				<!-- 聊天消息列表 -->
				<view class="message-list">
					<view v-for="(msg, index) in messages" :key="index" class="message-item" :class="msg.role">
						<!-- AI头像在左侧 -->
						<image class="avatar" v-if="msg.role === 'assistant'" :src="'/static/qcu_logo.jpg'"></image>
						<view class="message-content">
							<text class="message-role">{{
                msg.role === 'user' ? (currentLang === 'zh' ? '你' : 'You') : 'ChatQCU'
              }}</text>
							<view class="message-text-wrapper">
								<!-- AI消息loading动画 -->
								<template v-if="msg.role === 'assistant' && isAIResponding && index === messages.length - 1 && !msg.content">
									<view class="ai-loading">
										<view class="ai-loading-dots">
											<view class="loading-dot"></view>
											<view class="loading-dot"></view>
											<view class="loading-dot"></view>
										</view>
									</view>
								</template>
								<template v-else>
									<markdown-renderer class="message-text" :content="msg.content"></markdown-renderer>
								</template>

								<!-- 消息操作按钮 -->
								<view class="message-actions" v-if="msg.role === 'assistant'">
									<view class="action-icon" @click.stop="copyMessage(msg.content)">
										<text class="icon-btn">📋</text>
									</view>
									<view class="action-icon" @click.stop="likeMessage(index)">
										<text class="icon-btn" :class="{ 'active-icon': msg.liked }">👍</text>
									</view>
									<view class="action-icon" @click.stop="dislikeMessage(index)">
										<text class="icon-btn" :class="{ 'active-icon': msg.disliked }">👎</text>
									</view>
									<!-- 添加重试按钮，仅在消息包含错误提示时显示 -->
									<view class="action-icon retry-btn" @click.stop="retryLastMessage()"
										v-if="msg.isError">
										<text class="icon-btn">🔄</text>
									</view>
								</view>

								<!-- 用户消息只显示复制按钮 -->
								<view class="message-actions" v-if="msg.role === 'user'">
									<view class="action-icon" @click.stop="copyMessage(msg.content)">
										<text class="icon-btn">📋</text>
									</view>
								</view>
							</view>
						</view>
						<!-- 用户头像在右侧 -->
						<image class="avatar" v-if="msg.role === 'user'" :src="'/static/user.png'"></image>
					</view>
				</view>

				<!-- 推荐问题列表，仅在没有消息时显示 -->
				<view class="question-list" v-if="messages.length === 0">
					<text class="try-ask-text">{{ t('chat.tryAsk') }}</text>
					<button class="question-btn" type="default" v-for="(item, index) in questions" :key="index"
						@click="sendQuestion(item)">
						{{ item }}
					</button>
				</view>
			</scroll-view>

			<!-- 滚动到底部按钮 -->
			<view class="scroll-to-bottom-btn" v-if="showScrollBottomBtn && messages.length > 0" @click="scrollToBottomAndResumeAuto">
				<text class="icon-btn scroll-down-icon">⬇</text>
			</view>

			<!-- 底部输入区 -->
			<view class="footer">
				<view class="input-area">
					<view class="button-group">
						<view class="upload-btn">
							<text class="icon-btn">📎</text>
						</view>
						<!--  这里的confirm 就是指回车发送消息执行的事件 -->
						<input class="input-box" maxlength="100000" type="text" v-model="inputMessage"
							:placeholder="t('chat.placeholder')" @confirm="handleSendButtonClick" @focus="handleInputFocus" @blur="handleInputBlur" />
						<!-- 注意按钮disabled的逻辑 -->
						<button class="send-message-btn" :class="{ active: inputMessage || isAIResponding }"
							:disabled="!inputMessage && !isAIResponding" @click="handleSendButtonClick">
							<view v-if="isAIResponding" class="icon-btn send-icon stop-icon">■</view>
							<view v-else class="icon-btn send-icon">⮞</view>
						</button>
					</view>
					<view class="action-buttons">
						<button class="action-btn" :class="{ active: activeButtons.think }" type="default"
							@click="handleButtonClick('think')">
							<text class="icon-btn">🔄</text>
							<text class="btn-text">{{ t('chat.thinking') }}</text>
						</button>
						<button class="action-btn" :class="{ active: activeButtons.search }" type="default"
							@click="handleButtonClick('search')">
							<text class="icon-btn">🔍</text>
							<text class="btn-text">{{ t('chat.search') }}</text>
						</button>

					</view>
				</view>
				<text class="tip-text">{{ t('chat.aiGeneratedTip') }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		nextTick,
		onUnmounted,
		computed,
		watch
	} from 'vue'
	// 导入Markdown渲染组件
	import MarkdownRenderer from '../../components/MarkdownRenderer.vue'
	// 复制文本插件
	import ClipboardJS from 'clipboard';
	// 导入语言包
	import zhLocale from '../../locales/zh.js'
	import enLocale from '../../locales/en.js'

	// 当前语言
	const currentLang = ref('zh') // 默认中文

	// 语言包
	const locales = {
		zh: zhLocale,
		en: enLocale
	}

	// 翻译函数
	const t = (key) => {
		const keys = key.split('.')
		let result = locales[currentLang.value]
		
		for (let k of keys) {
			if (result[k] === undefined) return key
			result = result[k]
		}
		
		return result
	}

	// 切换语言
	const toggleLanguage = () => {
		currentLang.value = currentLang.value === 'zh' ? 'en' : 'zh'
		// 保存语言偏好
		uni.setStorageSync('appLanguage', currentLang.value)
	}

	// 悬浮球组件引用
	const dui_float_ball = ref(null)

	// 悬浮球背景样式
	const ballStyle = ref({
		background: "url('/static/qcu_logo_circle.jpg') center center / cover no-repeat, #fff",
		borderRadius: '50%',
		boxShadow: '0 6px 16px rgba(0, 0, 0, 0.2)',
		overflow: 'hidden',
		padding: 0,
		margin: 0,
		border: '2px solid #ffffff',
		transition: 'all 0.3s ease',
		width: '100rpx',
		height: '100rpx'
	})

	const isAIResponding = ref(false) // 判断AI是否在输出

	let eventSource // 提前声明，用于让方法关闭

	// 结束AI输出
	const stopAIResponding = () => {
		eventSource.close(); // 关闭流式连接
		isAIResponding.value = false; // 停止AI输出
	};

	// 结束输出的逻辑
	const handleSendButtonClick = () => {
		if (isAIResponding.value) {
			console.log('结束AI输出')
			stopAIResponding(); // 结束AI输出
		} else {
			console.log('开始AI输出')
			isAIResponding.value = true;
			handleSend(); // 处理发送消息
		}
	}

	// API基础URL
	const apiBaseUrl = 'http://localhost:8080'

	// App名称
	const appName = computed(() => t('common.appName'))
	
	// 定义0是V3,1是R1
	let modelFlag = 'v3' // 默认使用v3模型
	// 聊天记录列表
	const chatList = ref([])
	// 当前聊天ID
	const currentChatId = ref('')
	// 触摸开始位置
	const touchStartX = ref(0)
	// 消息列表
	const messages = ref([])
	// 输入框消息
	const inputMessage = ref('')
	// 滚动位置
	const scrollTop = ref(0)
	// 聊天滚动视图引用
	const chatScrollView = ref(null)
	// 侧边栏是否打开（仅为兼容，实际不使用侧边栏）
	const sidebarOpen = ref(false)
	// 加载状态
	const isLoading = ref(false)

	// 功能按钮状态
	const activeButtons = ref({
		think: false,
		search: false,
	})

	// 推荐问题列表 - 修改为ref，不再从本地语言文件获取
	const questions = ref([])
	
	// 加载推荐问题
	const loadSuggestQuestions = () => {
		console.log('开始请求推荐问题API...');
		console.log('请求URL:', `${apiBaseUrl}/system/suggest/question/api/enabled`);
		
		uni.request({
			url: `${apiBaseUrl}/system/suggest/question/api/enabled`,
			method: 'GET',
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				console.log('推荐问题API响应:', JSON.stringify(res));
				
				if (res.statusCode === 200) {
					// 详细检查响应数据结构
					if (res.data && (res.data.code === 200 || res.data.code === undefined) && 
						(res.data.data || res.data.rows || Array.isArray(res.data))) {
						
						// 处理不同的响应格式
						let dataArray = [];
						
						if (Array.isArray(res.data)) {
							// 直接是数组
							dataArray = res.data;
						} else if (res.data.data && Array.isArray(res.data.data)) {
							// 标准格式 {code: 200, msg: 'success', data: [...]}
							dataArray = res.data.data;
						} else if (res.data.rows && Array.isArray(res.data.rows)) {
							// 分页格式 {code: 200, rows: [...], total: 10}
							dataArray = res.data.rows;
						}
						
						if (dataArray.length > 0) {
							// 检查数据项格式，确保有contentZh和contentEn字段
							if (dataArray[0].contentZh !== undefined && dataArray[0].contentEn !== undefined) {
								const questionList = dataArray.map(item => {
									return currentLang.value === 'zh' ? item.contentZh : item.contentEn;
								});
								
								console.log('成功解析推荐问题:', questionList.length);
								questions.value = questionList;
							} else {
								console.error('API返回数据格式不正确，缺少contentZh或contentEn字段:', dataArray[0]);
								questions.value = t('questions');
								console.log('已回退使用本地问题列表');
							}
						} else {
							console.warn('API返回的数据数组为空');
							questions.value = t('questions');
							console.log('已回退使用本地问题列表');
						}
					} else if (res.data && res.data.code === 401) {
						console.error('API认证失败(401)，请检查后端安全配置:', res.data.msg);
						questions.value = t('questions');
						console.log('已回退使用本地问题列表');
					} else {
						console.error('API响应格式不符合预期:', res.data);
						questions.value = t('questions');
						console.log('已回退使用本地问题列表');
					}
				} else {
					console.error('API请求失败，状态码:', res.statusCode);
					questions.value = t('questions');
					console.log('已回退使用本地问题列表');
				}
			},
			fail: (err) => {
				console.error('请求推荐问题接口网络错误:', err);
				questions.value = t('questions');
				console.log('已回退使用本地问题列表');
			}
		});
	};

	// 状态栏高度
	const statusBarHeight = ref(20);

	// 当前长按选中的聊天ID
	const selectedChatId = ref('')
	// 操作菜单是否显示
	const showActionMenu = ref(false)
	// 是否显示滚动到底部按钮
	const showScrollBottomBtn = ref(true)
	// 滚动距离阈值
	const scrollThreshold = 200

	// 滚动高度，根据屏幕动态计算
	const scrollHeight = ref(0);

	// 在组件挂载时计算滚动高度
	onMounted(() => {
		// 获取状态栏高度
		try {
			const sysInfo = uni.getSystemInfoSync();
			statusBarHeight.value = sysInfo.statusBarHeight || 20;
			// 计算滚动区域高度，减去底部输入框高度
			scrollHeight.value = sysInfo.windowHeight - 180; // 减去输入框和其他UI元素高度
		} catch (e) {
			console.error('获取状态栏和窗口高度失败', e);
			scrollHeight.value = 500; // 默认值
		}

		// 初始化悬浮菜单状态
		showFloatMenu.value = false;
		console.log('初始化悬浮菜单状态:', showFloatMenu.value);
		
		// 直接创建新的空聊天，不从存储加载
		console.log('初始化新的聊天会话');
		createNewChatLocal();
		
		// 加载推荐问题
		loadSuggestQuestions();
		
		// 完成初始化后滚动到底部
		nextTick(() => {
			if (messages.value.length > 0) {
				scrollToBottom();
			}
		});
		
		// 添加对switchChat事件的监听
		uni.$on('switchChat', ({conversationId}) => {
			console.log('收到切换聊天事件，聊天ID:', conversationId);
			if (conversationId) {
				// 检查聊天是否已在列表中
				const chatExists = chatList.value.some(
					chat => chat.id === conversationId || chat.conversationId === conversationId
				);
				
				if (!chatExists) {
					console.log('聊天不在列表中，尝试添加到列表:', conversationId);
					// 从API获取聊天详情
					uni.request({
						url: `${apiBaseUrl}/api/conversation/${conversationId}`,
						method: 'GET',
						success: (res) => {
							if (res.statusCode === 200 && res.data && res.data.data) {
								// 将聊天添加到列表的开头
								const chatInfo = res.data.data;
								const newChat = {
									id: chatInfo.conversationId || conversationId,
									conversationId: chatInfo.conversationId || conversationId,
									title: chatInfo.title || t('chat.newChat'),
									time: chatInfo.updateTime || formatTime(new Date()),
									isPinned: false
								};
								
								// 添加到列表开头
								chatList.value.unshift(newChat);
								console.log('已将聊天添加到列表:', newChat);
							} else {
								// 如果API获取失败，仍然创建一个基本的聊天对象
								const fallbackChat = {
									id: conversationId,
									conversationId: conversationId,
									title: t('chat.newChat'),
									time: formatTime(new Date()),
									isPinned: false
								};
								
								chatList.value.unshift(fallbackChat);
								console.log('API获取失败，创建基本聊天对象:', fallbackChat);
							}
							
							// 无论如何，都尝试切换到这个聊天
							switchChat(conversationId);
						},
						fail: (err) => {
							console.error('获取聊天详情失败:', err);
							// 创建一个基本的聊天对象
							const fallbackChat = {
								id: conversationId,
								conversationId: conversationId,
								title: t('chat.newChat'),
								time: formatTime(new Date()),
								isPinned: false
							};
							
							chatList.value.unshift(fallbackChat);
							console.log('请求失败，创建基本聊天对象:', fallbackChat);
							
							// 无论如何，都尝试切换到这个聊天
							switchChat(conversationId);
						}
					});
				} else {
					// 如果已在列表中，直接切换
					switchChat(conversationId);
				}
			}
		});
		
		// 添加对createNewChat事件的监听
		uni.$on('createNewChat', () => {
			console.log('收到创建新聊天事件');
			createNewChatLocal();
		});
		
		// 加载保存的语言偏好
		const savedLang = uni.getStorageSync('appLanguage')
		if (savedLang) {
			currentLang.value = savedLang
		}
		
		// 添加窗口大小变化监听，确保在屏幕旋转或键盘弹出后重新滚动到底部
		uni.onWindowResize(() => {
			if (isAIResponding.value || messages.value.length > 0) {
				setTimeout(() => {
					scrollToBottom();
				}, 300);
			}
		});
	})
	
	// 组件卸载时移除事件监听
	onUnmounted(() => {
		uni.$off('switchChat');
		uni.$off('createNewChat');
		uni.offWindowResize();
	})

	// 添加自动滚动控制标志
	const autoScroll = ref(true);

	// 防抖函数，避免短时间内多次调用滚动
	const debounce = (fn, delay) => {
		let timer = null;
		return function(...args) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			}, delay);
		}
	}

	// 使用防抖版本的滚动函数
	const debouncedScrollToBottom = debounce(() => {
		if (autoScroll.value) {
			scrollToBottom();
		}
	}, 200);

	// 处理滚动事件
	const onScroll = (e) => {
		const scrollTop = e.detail.scrollTop
		const scrollHeight = e.detail.scrollHeight
		const clientHeight = e.detail.scrollHeight * 0.8 
		
		// 判断是否滚动接近底部
		const distanceToBottom = scrollHeight - scrollTop - clientHeight
		const isNearBottom = distanceToBottom < 200 
		
		// 根据滚动位置决定是否自动滚动
		// 当用户主动向上滚动时，暂停自动滚动
		if (isNearBottom) {
			autoScroll.value = true; // 用户接近底部，恢复自动滚动
			showScrollBottomBtn.value = false;
		} else {
			// 用户远离底部且不是AI回复时，暂停自动滚动
			if (!isAIResponding.value) {
				autoScroll.value = false;
			}
			
			// 显示回到底部按钮
			if (messages.value.length > 0) {
				showScrollBottomBtn.value = true;
			}
			
			// 如果AI正在回复，且最后一条消息是AI的，保持自动滚动
			const lastMsg = messages.value[messages.value.length - 1];
			if (isAIResponding.value && lastMsg && lastMsg.role === 'assistant') {
				autoScroll.value = true;
				debouncedScrollToBottom();
			}
		}
	}

	// 点击滚动到底部按钮 - 恢复自动滚动
	const scrollToBottomAndResumeAuto = () => {
		autoScroll.value = true;
		scrollToBottom();
	}

	// 加载更多消息（上拉加载）- 空实现，保留接口
	const loadMoreMessages = () => {
		// 目前没有加载更多消息的功能
		console.log('上拉加载更多消息功能未实现');
	}

	// 生成唯一ID
	const generateId = () => {
		return 'chat_' + Date.now() + '_' + Math.floor(Math.random() * 1000)
	}

	// 格式化时间
	const formatTime = date => {
		const now = new Date(date)
		return (
			now.getFullYear() +
			'-' +
			String(now.getMonth() + 1).padStart(2, '0') +
			'-' +
			String(now.getDate()).padStart(2, '0') +
			' ' +
			String(now.getHours()).padStart(2, '0') +
			':' +
			String(now.getMinutes()).toString().padStart(2, '0')
		)
	}

	// 切换侧边栏
	const toggleSidebar = () => {
		// 如果侧边栏即将关闭，保存当前聊天
		if (sidebarOpen.value) {
			saveCurrentChat();
		}
		sidebarOpen.value = !sidebarOpen.value;
	}

	// 添加触摸响应变量
	const touchStartTime = ref(0)
	const isLongPress = ref(false)
	const touchMoved = ref(false)

	// 处理触摸开始事件
	const handleTouchStart = (e) => {
		touchStartTime.value = Date.now()
		isLongPress.value = false
		touchMoved.value = false
		
		// 添加触摸反馈效果
		ballStyle.value.transform = 'scale(0.95)'
	}

	// 处理触摸移动事件
	const handleTouchMove = (e) => {
		if (!sidebarOpen.value) return

		const currentX = e.touches[0].clientX
		const diffX = currentX - touchStartX.value

		// 如果是向左滑动且滑动距离超过50px，关闭侧边栏
		if (diffX < -50) {
			sidebarOpen.value = false
		}
	}

	// 切换对话
	const switchChat = (conversationId) => {
		console.log('开始切换对话，ID:', conversationId);
		
		// 确保 conversationId 是字符串
		const chatId = String(conversationId);
		console.log('规范化后的聊天ID:', chatId);
		
		// 更新当前聊天ID
		currentChatId.value = chatId;
		isLoading.value = true;
		
		// 根据ID从列表中找到聊天信息
		const chatInList = chatList.value.find(
			chat => chat.id === chatId || chat.conversationId === chatId
		);
		
		console.log('在聊天列表中查找结果:', chatInList ? '找到' : '未找到');
		
		if (chatInList) {
			// 使用空消息列表，因为我们不再从存储加载
			messages.value = [];
			isLoading.value = false;
			scrollToBottom();
			
			// 尝试从API获取该会话的消息
			uni.request({
				url: `${apiBaseUrl}/api/conversation/${chatId}/messages`,
				method: 'GET',
				data: {
					pageNum: 1,
					pageSize: 50, // 加载较多的消息
					isDeleted: 0 // 只加载未删除的消息
				},
				success: (res) => {
					console.log('API返回结果:', res.statusCode);
					if (res.statusCode === 200 && res.data && res.data.data && res.data.data.data) {
						// 将API返回的消息格式转换为适合UI显示的格式
						const chatMessages = res.data.data.data.map(msg => {
							return {
								role: msg.userQuestion ? 'user' : 'assistant',
								content: msg.userQuestion || msg.aiResponse,
								time: msg.timestamp || msg.createTime,
								liked: false,
								disliked: false
							};
						});
						// 由于API返回的消息是倒序的，需要反转回正序显示
						messages.value = chatMessages.reverse();
						console.log('API加载的消息数量:', messages.value.length);
						
						// 确保在消息加载完成后滚动到底部，使用两次调用确保可靠性
						nextTick(() => {
							scrollToBottom();
							// 延迟再次滚动以防内容渲染延迟
							setTimeout(() => {
								scrollToBottom();
							}, 300);
						});
					} else {
						console.error('加载会话消息失败', res);
						uni.showToast({
							title: '加载会话消息失败',
							
							icon: 'none'
						});
						// 使用空消息列表
						messages.value = [];
					}
				},
				fail: (err) => {
					console.error('加载会话消息请求失败', err);
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					});
					// 使用空消息列表
					messages.value = [];
				},
				complete: () => {
					isLoading.value = false;
					// 确保即使接口失败也尝试滚动到底部
					scrollToBottom();
				}
			});
		} else {
			// 如果聊天不在列表中，使用空消息列表
			messages.value = [];
			isLoading.value = false;
			scrollToBottom();
		}
	}

	// 保存聊天列表到临时存储
	const saveChatList = () => {
		// 使用临时变量存储，不再使用本地存储
		// 临时存储不会持久化，刷新页面后会消失
		console.log('保存聊天列表到临时存储');
	}

	// 保存当前聊天消息（使用临时存储）
	const saveCurrentChat = () => {
		// 使用临时变量存储，不再使用本地存储
		console.log('保存当前聊天到临时存储');
	}

	// 滚动到底部
	const scrollToBottom = () => {
		nextTick(() => {
			// 使用更可靠的方式滚动到底部
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this)
				query
					.select('#chat-container')
					.boundingClientRect(data => {
						if (data) {
							// 计算一个足够大的值确保滚动到底部
							scrollTop.value = data.scrollHeight * 2
							// 隐藏滚动到底部按钮
							showScrollBottomBtn.value = false
							
							// 使用uni-app原生API滚动
							try {
								// 使用更稳定的方式滚动到底部
								uni.createSelectorQuery()
									.select('#chat-container')
									.fields({
										size: true,
										scrollOffset: true
									}, (res) => {
										if (res) {
											// 设置滚动到底部，多加一些高度确保到底
											scrollTop.value = res.scrollHeight * 2;
										}
									})
									.exec();
								
								// 在移动设备上添加平滑滚动效果
								uni.pageScrollTo({
									scrollTop: data.scrollHeight,
									duration: 300  // 平滑滚动的时间，单位ms
								});
							} catch (e) {
								console.error('滚动时出错:', e)
							}
						}
					})
					.exec()
			}, 150) // 增加延时，确保DOM更新完成
		})
	}

	// 发送预览问题
	const sendQuestion = question => {
		console.log(question)
		inputMessage.value = question
		handleSendButtonClick()
		// 确保发送预设问题后也滚动到底部
		scrollToBottom()
	}

	// 处理按钮点击
	const handleButtonClick = type => {
		modelFlag = modelFlag === 'v3' ? 'r1' : 'v3'
		console.log('现在使用的模型: ', modelFlag === 'v3' ? 'V3' : 'R1')
		if (type === 'think') {
			activeButtons.value.think = !activeButtons.value.think
		} else if (type === 'search') {
			activeButtons.value.search = !activeButtons.value.search
		}
	}

	// 复制消息内容
	const copyMessage = (content) => {
		// 去除HTML标签，获取纯文本
		const plainText = content
			.replace(/<[^>]+>/g, '') // 移除所有HTML标签
			.replace(/&lt;/g, '<')
			.replace(/&gt;/g, '>')
			.replace(/&amp;/g, '&')
			.replace(/&quot;/g, '"')
			.replace(/&#039;/g, "'")
			.replace(/<br>/g, '\n'); // 将<br>转换回换行符

		uni.setClipboardData({
			data: plainText,
			success: () => {
				uni.showToast({
					title: '复制成功',
					icon: 'success',
					duration: 2000
				});
			}
		});
	}

	// 点赞消息
	const likeMessage = (index) => {
		if (!messages.value[index].liked) {
			messages.value[index].liked = true;
			messages.value[index].disliked = false;
			uni.showToast({
				title: '感谢您的反馈',
				icon: 'none',
				duration: 1500
			});
			// 这里可以添加向后端发送反馈的逻辑
			saveCurrentChat();
		} else {
			messages.value[index].liked = false;
			saveCurrentChat();
		}
	}

	// 不喜欢消息
	const dislikeMessage = (index) => {
		if (!messages.value[index].disliked) {
			messages.value[index].disliked = true;
			messages.value[index].liked = false;
			uni.showToast({
				title: '感谢您的反馈',
				icon: 'none',
				duration: 1500
			});
			// 这里可以添加向后端发送反馈的逻辑
			saveCurrentChat();
		} else {
			messages.value[index].disliked = false;
			saveCurrentChat();
		}
	}

	// 重试最后一条消息
	const retryLastMessage = () => {
		// 找到最后一条用户消息
		const lastUserMessageIndex = [...messages.value].reverse().findIndex(msg => msg.role === 'user');
		if (lastUserMessageIndex !== -1) {
			// 计算实际索引（从后往前数）
			const actualIndex = messages.value.length - 1 - lastUserMessageIndex;
			const lastUserMessage = messages.value[actualIndex];
			
			// 移除最后一条AI回复（通常是错误消息）
			messages.value.pop();
			
			// 将用户消息内容设置到输入框
			inputMessage.value = lastUserMessage.content;
			
			// 触发发送
			handleSendButtonClick();
			
			// 确保滚动到底部
			scrollToBottom();
		} else {
			uni.showToast({
				title: '没有找到可以重试的消息',
				icon: 'none',
				duration: 2000
			});
		}
	}

	// 在发送消息前优化聊天体验的准备工作
	const prepareMessageSending = () => {
		// 清除输入框
		const messageToBeSent = inputMessage.value.trim();
		inputMessage.value = '';
		
		// 如果滚动按钮显示，说明用户当前不在底部
		// 先滚动到底部再发送消息，提升用户体验
		if (showScrollBottomBtn.value) {
			scrollToBottom();
			// 延迟300ms使滚动生效后再继续
			return new Promise(resolve => {
				setTimeout(() => {
					resolve(messageToBeSent);
				}, 300);
			});
		}
		
		return Promise.resolve(messageToBeSent);
	}

	// 处理发送消息，更新为保存到当前聊天
	const handleSend = async () => {
		console.log('开始发送消息')
		if (!inputMessage.value.trim()) return
		
		// 确保有当前聊天ID，如果没有则创建新聊天
		if (!currentChatId.value) {
			createNewChatLocal();
		}
		
		// 优化发送前的滚动体验
		const messageContent = await prepareMessageSending();
		if (!messageContent) return; // 防止空消息
		
		const userMessage = {
			role: 'user',
			content: messageContent,
			model: modelFlag // 添加模型信息
		}
		
		messages.value.push(userMessage)
		
		// 在添加用户消息后立即滚动到底部
		scrollToBottom()
		
		// 隐藏滚动到底部按钮
		showScrollBottomBtn.value = false
		
		// 响应式，确保数据变化，视图自动更新。
		const assistantMessage = reactive({
			role: 'assistant',
			content: '',
			liked: false,
			disliked: false,
			isError: false // 添加错误标志
		})

		// 发送用户输入的消息
		const question = encodeURIComponent(messageContent)

		try {
			// 使用API直接发送请求
			eventSource = new EventSource(
				`${apiBaseUrl}/api/chat/stream?question=${question}`
			)
			
			messages.value.push(assistantMessage)
			
			// 添加AI消息后再次滚动到底部
			scrollToBottom()

			// 接收服务器发送的事件
			eventSource.addEventListener('message', event => {
				if (event.data === '[DONE]') {
					eventSource.close()
					isAIResponding.value = false // 重置状态为非响应状态
					
					// AI回复完成后再次滚动到底部
					setTimeout(() => {
						scrollToBottom();
					}, 300);
					return
				}

				try {
					// 简化处理逻辑，直接拼接内容
					const newText = event.data;
					assistantMessage.content += newText;

					// 如果允许自动滚动，则滚动到底部
					if (autoScroll.value && assistantMessage.content.length % 30 === 0) {
						debouncedScrollToBottom();
					}
				} catch (e) {
					console.error('处理消息时出错:', e)
				}
			})

			eventSource.addEventListener('error', event => {
				console.error('事件流错误:', event)
				eventSource.close()
				isAIResponding.value = false // 重置状态为非响应状态
				assistantMessage.isError = true
				assistantMessage.content =
					'抱歉，发生了错误，请稍后再试。'
			})
		} catch (error) {
			console.error('发送消息时出错:', error)
			isAIResponding.value = false // 重置状态为非响应状态
			
			// 在消息列表中添加错误提示
			messages.value.push({
				role: 'assistant',
				content: '抱歉，发生了错误，请稍后再试。',
				isError: true
			})
		}
	}

	// 滚动到底部事件处理
	const onScrollToLower = () => {}

	// 处理图片加载错误
	const handleImageError = e => {
		console.error('图片加载失败')
	}

	// 长按聊天记录
	const handleLongPress = (chatId) => {
		selectedChatId.value = chatId
		showActionMenu.value = true
	}

	// 重命名聊天
	const renameChat = () => {
		const chat = chatList.value.find(item => item.id === selectedChatId.value)
		if (!chat) return

		uni.showModal({
			title: '重命名对话',
			content: '',
			editable: true,
			placeholderText: chat.title,
			success: (res) => {
				if (res.confirm && res.content) {
					// 更新标题
					const index = chatList.value.findIndex(item => item.id === selectedChatId.value)
					if (index !== -1) {
						chatList.value[index].title = res.content
						saveChatList()
					}
				}
			},
			complete: () => {
				showActionMenu.value = false
			}
		})
	}

	// 置顶/取消置顶聊天
	const pinChat = () => {
		const index = chatList.value.findIndex(item => item.id === selectedChatId.value)
		if (index === -1) return

		const chat = chatList.value[index]

		// 如果已经置顶，则取消置顶
		if (chat.isPinned) {
			chat.isPinned = false
			saveChatList()

			uni.showToast({
				title: '已取消置顶',
				icon: 'success',
				duration: 1500
			})
		} else {
			// 标记为置顶
			chat.isPinned = true

			// 从数组中移除该聊天
			chatList.value.splice(index, 1)
			// 添加到数组开头
			chatList.value.unshift(chat)
			saveChatList()

			uni.showToast({
				title: '已置顶',
				icon: 'success',
				duration: 1500
			})
		}

		showActionMenu.value = false
	}

	// 删除聊天
	const deleteChat = () => {
		uni.showModal({
			title: '删除对话',
			content: '确定要删除这个对话吗？此操作不可恢复。',
			success: (res) => {
				if (res.confirm) {
					const index = chatList.value.findIndex(item => item.id === selectedChatId.value)
					if (index !== -1) {
						// 从列表中删除
						chatList.value.splice(index, 1)
						
						// 如果删除的是当前聊天，则切换到其他聊天或创建新聊天
						if (selectedChatId.value === currentChatId.value) {
							if (chatList.value.length > 0) {
								switchChat(chatList.value[0].id || chatList.value[0].conversationId)
							} else {
								createNewChatLocal();
							}
						}

						uni.showToast({
							title: '已删除',
							icon: 'success',
							duration: 1500
						})
					}
				}
			},
			complete: () => {
				showActionMenu.value = false
			}
		})
	}

	// 关闭操作菜单
	const closeActionMenu = () => {
		showActionMenu.value = false
	}

	// 获取当前选中的聊天
	const getSelectedChat = () => {
		return chatList.value.find(item => item.id === selectedChatId.value)
	}

	// 悬浮球菜单状态
	const showFloatMenu = ref(false)
	const closingMenu = ref(false)

	// 悬浮球菜单项
	const floatMenuItems = computed(() => [
		{ icon: '👤', action: 'profile', label: t('menu.profile') },
		{ icon: '📚', action: 'history', label: t('menu.history') },
		{ icon: '✚', action: 'newChat', label: t('menu.newChat') },
		{ icon: '🌐', action: 'language', label: currentLang.value === 'zh' ? 'English' : '中文' }
	])

	// 切换悬浮菜单显示状态
	const toggleFloatMenu = () => {
		console.log('Toggle float menu, current state:', showFloatMenu.value);
		if (showFloatMenu.value) {
			// 关闭菜单时，先设置关闭动画状态
			closingMenu.value = true;
			// 等动画完成后，真正关闭菜单
			setTimeout(() => {
				showFloatMenu.value = false;
				closingMenu.value = false;
			}, 300); // 300ms动画时间
		} else {
			// 打开菜单
			showFloatMenu.value = true;
		}
	}

	// 处理悬浮球触摸事件
	const handleFloatBallTouch = () => {
		console.log('悬浮球点击事件触发');
		toggleFloatMenu();
	}

	// 计算悬浮菜单项的位置（不再需要动态计算，改为固定布局）
	const calculatePosition = (index) => {
		// 保留此函数以便未来需要时使用，但现在使用CSS固定布局
		return {};
	}

	// 处理悬浮菜单点击事件
	const handleFloatMenuClick = (action) => {
		console.log('悬浮菜单点击事件：', action);
		switch (action) {
			case 'profile':
				try {
					// 关闭浮动菜单
					showFloatMenu.value = false;
					// 跳转到个人中心页面
					uni.navigateTo({
						url: '/pages/profile/profile'
					});
				} catch (error) {
					console.error('导航异常:', error);
				}
				break;
			case 'history':
				// 打开聊天记录页面
				showFloatMenu.value = false;
				uni.navigateTo({
					url: '/pages/history/history'
				});
				break;
			case 'newChat':
				// 关闭浮动菜单
				showFloatMenu.value = false;
				// 创建新聊天
				createNewChatLocal();
				break;
			case 'language':
				// 切换语言
				toggleLanguage();
				break;
			default:
				console.log('未知的菜单操作:', action);
				break;
		}
	}

	// 创建新聊天（临时版本）
	const createNewChatLocal = () => {
		// 显示加载提示
		uni.showLoading({
			title: t('common.loading'),
			mask: true
		});
		
		try {
			// 生成一个新的会话ID
			const newChatId = 'local_chat_' + Date.now();
			
			// 创建新的聊天会话对象
			const newChat = {
				id: newChatId,
				conversationId: newChatId,
				title: t('chat.newChat'),
				time: formatTime(new Date()),
				messages: [],
				isPinned: false
			};
			
			// 将新会话添加到会话列表开头
			
			chatList.value.unshift(newChat);
			
			// 清空当前消息列表
			messages.value = [];
			
			// 将当前会话ID设置为新会话
			currentChatId.value = newChatId;
			
			uni.showToast({
				title: t('chat.newChat'),
				icon: 'success',
				duration: 1500
			});
			
		} catch (error) {
			console.error('创建新会话失败', error);
			uni.showToast({
				title: t('chat.error'),
				icon: 'none',
				duration: 2000
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
		}
	}

	// 添加对聊天记录数据结构的管理
	const getChatMessages = (chatId) => {
		// 直接返回空数组，不再从存储获取
		return []; // 不从存储加载，返回空数组
	}

	// 保存特定聊天的消息到临时存储
	const saveChatMessages = (chatId, messagesData) => {
		// 使用临时变量存储，不再使用本地存储
		console.log(`保存聊天 ${chatId} 的消息到临时存储`);
	}

	// 格式化日期
	const formatDate = (date) => {
		const year = date.getFullYear()
		const month = (date.getMonth() + 1).toString().padStart(2, '0')
		const day = date.getDate().toString().padStart(2, '0')
		return `${year}-${month}-${day}`
	}

	// 从API加载聊天列表
	const loadChatList = () => {
		uni.request({
			url: `${apiBaseUrl}/api/conversation/list?pageNum=1&pageSize=20`,
			method: 'GET',
			success: (res) => {
				if (res.statusCode === 200 && res.data && res.data.data) {
					// 处理会话列表数据
					chatList.value = res.data.data || [];
					
					// 如果有会话，自动打开第一个
					if (chatList.value.length > 0 && !currentChatId.value) {
						switchChat(chatList.value[0].conversationId);
					}
				} else {
					console.error('获取会话列表失败', res);
				}
			},
			fail: (err) => {
				console.error('获取会话列表请求失败', err);
			}
		});
	};

	// 获取聊天预览文本
	const getChatPreview = (chat) => {
		if (!chat.messages || chat.messages.length === 0) {
			return '开始新的对话...';
		}
		// 获取最后一条消息
		const lastMsg = chat.messages[chat.messages.length - 1];
		// 截取内容前30个字符作为预览
		return lastMsg.content.length > 30 ? 
			lastMsg.content.substring(0, 30) + '...' : 
			lastMsg.content;
	}
	
	// 获取相对时间
	const getRelativeTime = (timeStr) => {
		const date = new Date(timeStr);
		const now = new Date();
		
		// 判断是否是今天
		if (date.toDateString() === now.toDateString()) {
			return formatTimeOnly(date);
		}
		
		// 判断是否是昨天
		const yesterday = new Date(now);
		yesterday.setDate(now.getDate() - 1);
		if (date.toDateString() === yesterday.toDateString()) {
			return '昨天';
		}
		
		// 判断是否是本周
		const daysDiff = Math.floor((now - date) / (1000 * 60 * 60 * 24));
		if (daysDiff < 7) {
			const days = ['日', '一', '二', '三', '四', '五', '六'];
			return '周' + days[date.getDay()];
		}
		
		// 其他情况返回MM-DD格式
		return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
	}
	
	// 格式化时间为HH:MM
	const formatTimeOnly = (date) => {
		return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
	}

	// 加载旧版本的通用消息记录
	const loadLegacyMessages = () => {
		// 不再从旧版本的存储中加载
		console.log('跳过加载旧消息记录');
		messages.value = [];
	}

	// 处理触摸结束事件
	const handleTouchEnd = (e) => {
		// 恢复大小
		ballStyle.value.transform = 'scale(1)'
		
		// 如果没有移动且不是长按，视为点击
		const touchDuration = Date.now() - touchStartTime.value
		if (!touchMoved.value && touchDuration < 500) {
			handleFloatBallTouch()
		}
	}

	// 处理触摸取消事件
	const handleTouchCancel = () => {
		// 恢复大小
		ballStyle.value.transform = 'scale(1)'
	}

	// 点击页面任意区域关闭菜单
	const closeMenuIfOpen = () => {
		if (showFloatMenu.value) {
			toggleFloatMenu();
		}
	}

	// 在输入框获得焦点和失去焦点时确保滚动
	const handleInputFocus = () => {
		// 输入框获得焦点时延迟滚动，等待键盘弹出
		setTimeout(() => {
			scrollToBottom();
		}, 300);
	}

	const handleInputBlur = () => {
		// 输入框失去焦点时也滚动一次
		setTimeout(() => {
			scrollToBottom();
		}, 300);
	}

	// 语言变更时重新加载推荐问题
	watch(currentLang, (newLang) => {
		// 保存语言设置到本地存储
		uni.setStorageSync('appLanguage', newLang);
		
		// 语言变更时重新获取推荐问题（以显示对应语言的问题）
		loadSuggestQuestions();
	});
</script>

<style>
	.logo {
		border: none;
	}

	.text-app-name-box {
		margin-top: 16rpx;
		margin-bottom: 22rpx;
		text-align: center;
	}

	.image-logo-content {
		text-align: center;
		border: none;
	}

	page {
		height: 100%;
	}

	.page {
		display: flex;
		height: 100%;
		background-color: #ffffff;
		position: relative;
		overflow: hidden;
	}

	/* 主内容区样式 */
	.main-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		width: 100%;
	}

	/* 头部样式 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #f0f0f0;
		background-color: #ffffff;
		z-index: 100;
		position: sticky;
		top: 0;
		left: 0;
		right: 0;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	}

	.header-left,
	.header-right {
		width: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		font-size: 20px;
		color: #333333;
		font-weight: 500;
		text-align: center;
		flex: 1;
	}

	/* 聊天容器样式 */
	.chat-container {
		flex: 1;
		padding: 30rpx 0; /* 移除左右padding，只保留上下padding */
		overflow-y: auto;
		background-color: #f9f9f9;
		margin-top: 20rpx;
	}

	/* 有消息时的聊天容器样式，占据更多空间 */
	.chat-container-expanded {
		margin-top: 0;
		padding-top: 10rpx;
	}

	.welcome-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
	}

	.welcome-text {
		font-size: 14px;
		color: #333333;
		line-height: 1.6;
		display: block;
	}

	/* 消息列表样式 */
	.message-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		padding: 0 16rpx; /* 给整个消息列表添加左右内边距 */
		width: 100%;
		box-sizing: border-box;
	}

	.message-item {
		display: flex;
		margin-bottom: 30rpx;
		width: 100%;
		align-items: flex-start;
		box-sizing: border-box;
		padding: 0; /* 移除左右padding */
	}

	.message-item.user {
		justify-content: flex-end;
	}

	.message-item.assistant {
		justify-content: flex-start;
	}

	.avatar {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		margin: 0; /* 移除默认边距 */
		flex-shrink: 0;
		object-fit: cover;
		border: 1px solid #f0f0f0;
	}

	/* 覆盖avatar样式 */
	.message-item .avatar {
		width: 60rpx !important;
		height: 60rpx !important;
		margin: 5rpx 16rpx !important; /* 统一设置左右边距为16rpx */
	}

	.message-content {
		max-width: 84%;
		width: auto;
		display: flex;
		flex-direction: column;
	}

	.message-role {
		font-size: 12px;
		color: #999999;
		margin-bottom: 8rpx;
		display: block;
		padding: 0 10rpx;
	}

	.message-text-wrapper {
		width: 100%;
		display: block;
	}

	.message-text {
		padding: 24rpx 28rpx;
		border-radius: 12rpx;
		font-size: 15px;
		line-height: 1.7;
		word-break: break-word;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
		width: 100%;
		box-sizing: border-box;
		display: block;
		overflow-wrap: break-word;
		hyphens: auto;
		letter-spacing: 0.2px;
	}

	.message-item.user .message-text {
		background-color: #4080ff;
		color: #ffffff;
		border-radius: 18rpx 4rpx 18rpx 18rpx;
		margin-right: 0;
	}

	.message-item.assistant .message-text {
		background-color: #ffffff;
		color: #333333;
		border-radius: 4rpx 18rpx 18rpx 18rpx;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		margin-left: 0;
	}

	.message-item.user .message-role {
		text-align: right;
	}

	.message-item.assistant .message-role {
		text-align: left;
	}

	/* 加载指示器样式 */
	.loading-indicator {
		display: flex;
		justify-content: center;
		margin: 20rpx 0;
	}

	.loading-dots {
		display: flex;
		gap: 10rpx;
	}

	.dot {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #2979ff;
		animation: bounce 1.4s infinite ease-in-out both;
	}

	.dot:nth-child(1) {
		animation-delay: -0.32s;
	}

	.dot:nth-child(2) {
		animation-delay: -0.16s;
	}

	@keyframes bounce {

		0%,
		80%,
		100% {
			transform: scale(0);
		}

		40% {
			transform: scale(1);
		}
	}

	/* 问题列表样式 */
	.question-list {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
		gap: 20rpx;
		padding: 20rpx 0;
	}

	.question-btn {
		text-align: left;
		background-color: #ffffff !important;
		border: 1px solid #e0e0e0 !important;
		border-radius: 12rpx !important;
		padding: 16rpx 24rpx !important;
		font-size: 14px;
		line-height: 1.2;
		color: #333333;
		transition: all 0.3s ease;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.question-btn:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		border-color: #2979ff !important;
	}

	/* 底部输入区样式 */
	.footer {
		padding: 20rpx 30rpx 30rpx;
		border-top: 1px solid #f0f0f0;
		background-color: #ffffff;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
	}

	.input-area {
		margin-bottom: 10rpx;
	}

	.button-group {
		display: flex;
		align-items: center;
		background-color: #f9f9f9;
		border-radius: 36rpx;
		padding: 10rpx 20rpx;
		margin-bottom: 20rpx;
		box-shadow: none;
		border: 1px solid #eeeeee;
		transition: all 0.25s ease;
	}

	.button-group:focus-within {
		border-color: #2979ff;
		background-color: #ffffff;
	}

	.upload-btn {
		padding: 10rpx;
		margin-right: 10rpx;
		opacity: 0.7;
		transition: opacity 0.3s ease;
	}

	.upload-btn:active {
		opacity: 1;
	}

	.input-box {
		flex: 1;
		height: 72rpx;
		font-size: 14px;
		background-color: transparent;
		color: #333333;
		padding: 0 10rpx;
	}

	.send-message-btn {
		width: 72rpx !important;
		height: 72rpx !important;
		min-width: 72rpx !important;
		border-radius: 50% !important;
		display: flex !important;
		align-items: center;
		justify-content: center;
		padding: 0 !important;
		margin: 0 !important;
		background-color: #f5f5f5 !important;
		transition: all 0.25s ease;
		border: 1px solid #e8e8e8 !important;
		box-shadow: none;
		transform: translateY(0);
	}

	.send-message-btn:active {
		transform: translateY(2px);
		background-color: #eaeaea !important;
	}

	.send-message-btn.active {
		background-color: #2979ff !important;
		border: none !important;
		box-shadow: none;
	}

	.send-message-btn.active:active {
		background-color: #2567db !important;
	}

	.send-message-btn .icon-btn {
		font-size: 16px;
		color: #999999;
		transition: all 0.3s ease;
	}

	.send-message-btn.active .icon-btn {
		color: #ffffff !important;
	}

	.action-buttons {
		display: flex;
		gap: 20rpx;
	}

	.action-btn {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #ffffff !important;
		border: 1px solid #e0e0e0 !important;
		border-radius: 36rpx !important;
		padding: 12rpx 0;
		transition: all 0.25s ease;
		font-size: 14px;
		line-height: 1.2;
		color: #333333;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);
		transform: translateY(0);
	}

	.action-btn:active {
		transform: translateY(2px);
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
	}

	.action-btn.active {
		background-color: #e6f2ff !important;
		border-color: #2979ff !important;
		box-shadow: 0 2px 6px rgba(41, 121, 255, 0.15);
	}

	.action-btn.active:active {
		background-color: #d9e9ff !important;
	}

	.action-btn.active .btn-text {
		color: #2979ff;
	}

	.btn-text {
		margin-left: 10rpx;
		font-size: 14px;
		font-weight: 500;
		transition: color 0.25s ease;
	}

	.tip-text {
		font-size: 12px;
		color: #999999;
		text-align: center;
		display: block;
	}

	/* 行内代码样式 */
	:not(pre)>code {
		font-family: 'Courier New', Courier, monospace;
		padding: 2rpx 6rpx;
		border-radius: 4rpx;
		font-size: 14px;
		background-color: transparent;
		border: 1px solid #eaeaea;
	}

	.message-text :deep(:not(pre) > code) {
		font-family: 'Courier New', Courier, monospace;
		padding: 2rpx 6rpx;
		border-radius: 4rpx;
		font-size: 14px;
		background-color: transparent;
		border: 1px solid #eaeaea;
	}

	.message-item.user .message-text :deep(:not(pre) > code) {
		background-color: transparent;
		color: #ffffff;
		border: 1px solid rgba(255, 255, 255, 0.2);
	}

	/* 图标按钮样式 */
	.icon-btn {
		font-size: 20px;
		display: inline-block;
		cursor: pointer;
	}

	.sidebar-header .icon-btn {
		font-size: 24px;
	}

	.header-left .icon-btn,
	.header-right .icon-btn {
		font-size: 24px;
	}

	.send-message-btn .icon-btn {
		font-size: 16px;
		color: #999999;
		transition: all 0.3s ease;
	}

	.send-message-btn.active .icon-btn {
		color: #ffffff !important;
	}

	.action-btn .icon-btn {
		font-size: 16px;
		margin-right: 5rpx;
		color: #666666;
		transition: color 0.25s ease;
	}

	.action-btn.active .icon-btn {
		color: #2979ff;
	}

	.message-item.user .message-text :deep(a),
	.message-item.user .message-text :deep(strong),
	.message-item.user .message-text :deep(em),
	.message-item.user .message-text :deep(pre) {
		color: #ffffff;
	}

	.message-item.user .message-text :deep(.code-block) {
		background-color: rgba(255, 255, 255, 0.2);
		color: #ffffff;
		padding: 10rpx;
		border-radius: 6rpx;
		font-family: monospace;
	}

	.message-item.assistant .message-text :deep(.code-block) {
		background-color: white;
		color: #333333;
		padding: 10rpx;
		border-radius: 6rpx;
		font-family: monospace;
		border: 1px solid #eaeaea;
	}

	/* 代码块容器样式 */
	.message-text :deep(pre) {
		margin: 16rpx 0;
		border-radius: 8rpx;
		overflow-x: auto;
		background-color: #ffffff;
		border: 1px solid #eaeaea;
		white-space: pre;
		-webkit-overflow-scrolling: touch;
		max-width: 100%;
		/* 确保水平滚动 */
		word-wrap: normal;
		word-break: keep-all;
		overflow-wrap: normal;
		position: relative;
		/* 为固定头部做准备 */
	}

	/* 代码块头部样式 */
	.message-text :deep(.code-block-header) {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8rpx 16rpx;
		background-color: #f5f5f5;
		border-bottom: 1px solid #eaeaea;
		font-size: 12px;
		color: #666;
		position: absolute;
		/* 使头部固定 */
		top: 0;
		left: 0;
		right: 0;
		z-index: 10;
		height: 36rpx;
		line-height: 36rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.message-text :deep(.code-language) {
		text-transform: uppercase;
		font-weight: bold;
		font-size: 12px;
		color: #444;
		letter-spacing: 0.5px;
	}

	.message-text :deep(.copy-code-btn) {
		cursor: pointer;
		padding: 4rpx 14rpx;
		border-radius: 4rpx;
		background-color: #e0e0e0;
		transition: all 0.2s ease;
		font-size: 12px;
		color: #333;
		font-weight: 500;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		justify-content: center;
		height: 30rpx;
		line-height: 30rpx;
		position: relative;
		/* 确保在滚动时保持可见 */
		z-index: 11;
		/* 确保在代码上方 */
		margin-left: 10rpx;
	}

	.message-text :deep(.copy-code-btn.copy-success) {
		background-color: rgba(76, 175, 80, 0.8);
		color: white;
	}

	.message-text :deep(.copy-code-btn:hover) {
		background-color: #d0d0d0;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		transform: translateY(-1px);
	}

	.message-text :deep(.copy-code-btn:active) {
		transform: translateY(1px);
		box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
	}

	.message-item.user .message-text :deep(.code-block-wrapper) {
		background-color: rgba(255, 255, 255, 0.05);
		border: 1px solid rgba(255, 255, 255, 0.2);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
	}

	.message-item.user .message-text :deep(.copy-code-btn.copy-success) {
		background-color: rgba(76, 175, 80, 0.8);
		color: white;
	}

	/* Prism.js 代码高亮样式 */
	pre[class*="language-"] {
		display: block;
		overflow-x: auto;
		padding: 16rpx;
		padding-top: 0;
		/* 为头部留出空间 */
		background: #ffffff;
		color: #333;
		border-radius: 8rpx;
		font-family: 'Courier New', Courier, monospace;
		font-size: 14px;
		line-height: 1.5;
		margin: 16rpx 0;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		border: 1px solid #eaeaea;
		white-space: pre;
		-webkit-overflow-scrolling: touch;
		max-width: 100%;
		/* 确保水平滚动 */
		word-wrap: normal;
		word-break: keep-all;
		overflow-wrap: normal;
		position: relative;
		/* 为固定头部做准备 */
	}

	code[class*="language-"] {
		font-family: 'Courier New', Courier, monospace;
		padding: 0;
		border-radius: 0;
		font-size: 14px;
		background-color: transparent;
		color: inherit;
		white-space: pre;
		/* 确保不换行 */
		word-wrap: normal;
		word-break: keep-all;
		overflow-wrap: normal;
		display: inline-block;
		min-width: 100%;
	}

	/* 确保代码块内的滚动条样式美观 */
	.message-text :deep(pre::-webkit-scrollbar) {
		height: 6rpx;
		background-color: #f5f5f5;
	}

	.message-text :deep(pre::-webkit-scrollbar-thumb) {
		background-color: #ddd;
		border-radius: 3rpx;
	}

	.message-text :deep(pre::-webkit-scrollbar-track) {
		background-color: #f5f5f5;
	}

	.message-item.user .message-text :deep(pre::-webkit-scrollbar-thumb) {
		background-color: rgba(255, 255, 255, 0.3);
	}

	.message-item.user .message-text :deep(pre::-webkit-scrollbar-track) {
		background-color: rgba(255, 255, 255, 0.1);
	}

	/* Prism.js 语法高亮颜色 */
	.token.comment,
	.token.prolog,
	.token.doctype,
	.token.cdata {
		color: #708090;
	}

	.token.punctuation {
		color: #999;
	}

	.token.namespace {
		opacity: 0.7;
	}

	.token.property,
	.token.tag,
	.token.boolean,
	.token.number,
	.token.constant,
	.token.symbol {
		color: #905;
	}

	.token.selector,
	.token.attr-name,
	.token.string,
	.token.char,
	.token.builtin {
		color: #690;
	}

	.token.operator,
	.token.entity,
	.token.url,
	.language-css .token.string,
	.style .token.string,
	.token.variable {
		color: #9a6e3a;
	}

	.token.atrule,
	.token.attr-value,
	.token.keyword {
		color: #07a;
	}

	.token.function,
	.token.class-name {
		color: #dd4a68;
	}

	.token.regex,
	.token.important {
		color: #e90;
	}

	.token.important,
	.token.bold {
		font-weight: bold;
	}

	.token.italic {
		font-style: italic;
	}

	.token.entity {
		cursor: help;
	}

	.scroll-down-icon {
		font-size: 36px;
		color: #2979ff;
		line-height: 1;
		margin-top: -10rpx;
	}

	/* 发送图标特殊样式 */
	.send-icon {
		font-weight: 600;
		font-size: 18px !important;
		transition: all 0.25s ease;
		color: #999 !important;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
	}

  /*暂停按钮*/
	.stop-icon {
		font-size: 24px !important;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		position: relative;
		top: 0;
		left: 0;
		line-height: 1;
		margin-top: -2px; /* 微调垂直位置 */
	}

	.send-message-btn.active .send-icon {
		color: #ffffff !important;
	}

	/* 代码块样式 */
	.code-block {
		background-color: white;
		padding: 15rpx;
		border-radius: 8rpx;
		font-family: monospace;
		font-size: 18rpx;
		white-space: pre;
		margin: 10rpx 0;
		overflow-x: auto;
		border: 1px solid #eaeaea;
		-webkit-overflow-scrolling: touch;
		/* 确保水平滚动 */
		word-wrap: normal;
		word-break: keep-all;
		overflow-wrap: normal;
		display: block;
		width: 100%;
	}

	/* 消息操作按钮样式 */
	.message-actions {
		display: flex;
		gap: 20rpx;
		margin-top: 10rpx;
		padding: 8rpx 0;
	}

	.message-item.user .message-actions {
		justify-content: flex-end;
	}

	.message-item.assistant .message-actions {
		justify-content: flex-start;
	}

	.action-icon {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.05);
		transition: all 0.2s ease;
	}

	.action-icon:active {
		transform: scale(0.95);
	}

	.action-icon .icon-btn {
		font-size: 28rpx;
		color: #666666;
	}

	.active-icon {
		background-color: #e6f2ff;
	}

	.active-icon .icon-btn {
		color: #2979ff;
	}

	.message-item.user .message-actions .action-icon {
		background-color: rgba(255, 255, 255, 0.2);
	}

	.message-item.user .message-actions .icon-btn {
		color: #ffffff;
	}

	.message-item.user .message-actions .active-icon {
		background-color: rgba(255, 255, 255, 0.4);
	}

	/* 操作菜单样式 */
	.action-menu {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1100;
		display: flex;
		justify-content: center;
		align-items: center;
		opacity: 0;
		visibility: hidden;
		transition: opacity 0.3s ease, visibility 0.3s ease;
	}

	.action-menu-show {
		opacity: 1;
		visibility: visible;
	}

	.action-menu-content {
		background-color: #ffffff;
		width: 300rpx;
		border-radius: 12rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	.action-menu-btn {
		width: 100%;
		padding: 24rpx 0;
		margin: 0;
		background-color: #ffffff !important;
		border: none !important;
		border-radius: 0 !important;
		font-size: 16px;
		color: #333333;
		text-align: center;
		position: relative;
	}

	.action-menu-btn::after {
		content: '';
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
		height: 1px;
		background-color: #f0f0f0;
	}

	.action-menu-btn:last-child::after {
		display: none;
	}

	.action-menu-btn:active {
		background-color: #f5f5f5 !important;
	}

	.action-menu-btn.delete-btn {
		color: #ff3b30;
	}

	/* Markdown样式 */
	.message-text :deep(h1),
	.message-text :deep(h2),
	.message-text :deep(h3),
	.message-text :deep(h4),
	.message-text :deep(h5),
	.message-text :deep(h6) {
		font-weight: bold;
		margin: 10rpx 0;
		line-height: 1.4;
	}

	.message-text :deep(h1) {
		font-size: 20px;
	}

	.message-text :deep(h2) {
		font-size: 18px;
	}

	.message-text :deep(h3) {
		font-size: 16px;
	}

	.message-text :deep(h4),
	.message-text :deep(h5),
	.message-text :deep(h6) {
		font-size: 14px;
	}

	.message-item.user .message-text :deep(li) {
		color: #ffffff;
	}

	/* Markdown 样式已移至 MarkdownRenderer 组件中 */



	/* 代码块相关样式已移至 MarkdownRenderer 组件中 */

	.message-text-wrapper {
		width: 100%;
		display: block;
	}

	.message-text {
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		font-size: 15px;
		line-height: 1.6;
		word-break: break-word;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
		width: 100%;
		box-sizing: border-box;
		display: block;
		overflow-wrap: break-word;
		hyphens: auto;
	}

	/* 段落和文本元素样式已移至 MarkdownRenderer 组件中 */

	.message-item.user .message-text {
		background-color: #4080ff;
		color: #ffffff;
		border-radius: 18rpx 4rpx 18rpx 18rpx;
		margin-right: 0;
	}

	.message-item.assistant .message-text {
		background-color: #ffffff;
		color: #333333;
		border-radius: 4rpx 18rpx 18rpx 18rpx;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		margin-left: 0;
	}



	.message-item.user {
		justify-content: flex-end;
		padding-left: 0;
		padding-right: 0;
	}

	.message-item.assistant {
		justify-content: flex-start;
		padding-right: 0;
		padding-left: 0;
	}

	/* 悬浮菜单样式 */
	.float-menu {
		position: absolute;
		width: auto;
		height: auto;
		z-index: 999;
		pointer-events: auto; /* 确保菜单可以接收点击事件 */
		left: 120rpx; /* 从悬浮球右侧弹出 */
		top: 0; /* 与悬浮球垂直中心对齐 */
		display: flex;
		flex-direction: row; /* 横向排列 */
		align-items: center;
		background-color: rgba(255, 255, 255, 0.98);
		border-radius: 40rpx;
		padding: 8rpx 16rpx;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.12);
		animation: menuFadeIn 0.3s ease forwards;
		border: 1px solid rgba(240, 240, 240, 0.8);
	}

	@keyframes menuFadeIn {
		0% {
			opacity: 0;
			transform: translateX(-20rpx);
		}
		100% {
			opacity: 1;
			transform: translateX(0);
		}
	}

	.float-menu-item {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2000;
		transition: all 0.2s ease;
		width: 70rpx;
		height: 70rpx;
		margin: 0 10rpx;
		pointer-events: auto;
	}

    .float-menu-icon {
		width: 60rpx;
		height: 60rpx;
		background-color: #ffffff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		transition: all 0.2s ease;
		border: 1px solid #f0f0f0;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}


	/* 保留所需的样式 */
	.ball-logo {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		object-fit: cover;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
		border: 1px solid #f0f0f0;
	}

	/* 悬浮球容器样式 */
	.float-ball-container {
		position: fixed;
		top: 50%;
		left: 20rpx;
		transform: translateY(-50%);
		z-index: 1000;
		width: auto;
		height: auto;
	}

	/* 悬浮球图片覆盖样式 */
	.ball-overlay-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		border-radius: 50%;
		z-index: 1;
		object-fit: cover;
		overflow: hidden;
		pointer-events: none;
		box-shadow: inset 0 0 10rpx rgba(0, 0, 0, 0.1);
	}

	/* 展开菜单样式 - 调整位置以匹配贴边后的悬浮球 */
	.expanded-menu {
		position: fixed;
		left: 80rpx; /* 调整距离左边的位置，考虑到球会缩进 */
		top: 50%;
		transform: translateY(-50%);
		width: 118rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
		overflow: hidden;
		animation: expandMenu 0.4s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
		z-index: 1000;
		border: 1px solid #f0f0f0;
	}

	/* 菜单关闭的动画 */
	.closing-menu {
		animation: closeMenu 0.3s ease forwards;
	}

	@keyframes closeMenu {
		0% {
			transform: translate(0, -50%) scale(1);
			opacity: 1;
		}
		100% {
			transform: translate(-30rpx, -50%) scale(0.9);
			opacity: 0;
		}
	}

	@keyframes expandMenu {
		0% {
			transform: translate(-30rpx, -50%) scale(0.9);
			opacity: 0;
		}
		100% {
			transform: translate(0, -50%) scale(1);
			opacity: 1;
		}
	}

	.menu-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 24rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.menu-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #333;
	}

	.close-btn {
		font-size: 36rpx;
		color: #999;
		line-height: 1;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.close-btn:active {
		background-color: #f5f5f5;
	}

	.menu-items {
		padding: 16rpx 0;
	}

	.menu-item {
		display: flex;
		align-items: center;
		padding: 20rpx 24rpx;
		transition: background-color 0.2s ease;
	}

	.menu-item:active {
		background-color: #f5f5f5;
	}

	.menu-icon {
		width: 60rpx;
		height: 60rpx;
		background-color: #f8f8f8;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 20rpx;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
	}

	.menu-label {
		font-size: 28rpx;
		color: #333;
	}

	.icon-text {
		font-size: 30rpx;
		line-height: 1;
	}

	/* 滚动到底部按钮样式 */
	.scroll-to-bottom-btn {
		position: fixed;
		right: 30rpx;
		bottom: 200rpx;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #ffffff;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 100;
		transition: all 0.3s ease;
		border: 1px solid #eaeaea;
		animation: fadeIn 0.3s ease forwards;
	}

	.scroll-to-bottom-btn:active {
		transform: translateY(4rpx);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.scroll-down-icon {
		font-size: 36rpx;
		color: #2979ff;
		font-weight: bold;
	}

	/* AI loading动画样式 */
	.ai-loading {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 38px;
		padding: 0 8px;
		margin: 10rpx 0;
	}

	.ai-loading-dots {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading-dot {
		width: 8px;
		height: 8px;
		margin: 0 4px;
		border-radius: 50%;
		background-color: #2979ff;
		opacity: 0.8;
		animation: loadingDotBounce 1.4s infinite ease-in-out both;
	}

	.loading-dot:nth-child(1) {
		animation-delay: -0.32s;
	}

	.loading-dot:nth-child(2) {
		animation-delay: -0.16s;
	}

	@keyframes loadingDotBounce {
		0%, 80%, 100% {
			transform: scale(0);
		}
		40% {
			transform: scale(1);
		}
	}

	/* 自定义悬浮球样式 */
	.custom-float-ball {
		position: absolute;
		top: -5px;  /* 扩大5px触摸区域 */
		left: -5px; /* 扩大5px触摸区域 */
		width: 110rpx; /* 稍微增大 */
		height: 110rpx; /* 稍微增大 */
		padding: 5px; /* 内边距增大触摸区，但视觉大小不变 */
	}

	/* 悬浮球隐藏状态 */
	.float-ball-hidden {
		animation: floatBallFadeOut 0.3s ease-out forwards;
	}

	/* 悬浮球出现动画 */
	@keyframes floatBallFadeIn {
		0% {
			opacity: 0;
			transform: scale(0.6);
		}
		70% {
			transform: scale(1.1);
		}
		100% {
			opacity: 1;
			transform: scale(1);
		}
	}

	/* 悬浮球隐藏动画 */
	@keyframes floatBallFadeOut {
		0% {
			opacity: 1;
			transform: scale(1);
		}
		100% {
			opacity: 0;
			transform: scale(0.6);
		}
	}

	/* 添加触摸反馈状态 */
	.custom-float-ball:active {
		opacity: 0.9;
		transform: scale(0.95);
	}

	.try-ask-text {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
		padding: 0 30rpx;
		display: block;
	}
</style>
